from jili.tool.convert import str2datetime
from jili.data.db import tradecal,get_calender,getdb_client
from jili.core import load
import os,datetime
def gen_k1m_f_bypkl(obj,start_datetime=None,end_datetime=None,bars_len=30,k1m_url=r"D:\data\future_k1m_self"):
    if start_datetime:
        start_datetime=str2datetime(start_datetime)
        if start_datetime.hour>=18:
            start_date=tradecal.getnexttradeday(start_datetime)
        else:
            start_date = tradecal.gettradeday(start_datetime)
        if end_datetime:
            end_datetime=str2datetime(end_datetime)
            if end_datetime.hour >= 18:
                end_date = tradecal.getnexttradeday(end_datetime)
            else:
                end_date = tradecal.gettradeday(end_datetime)
            for d in get_calender(start_date,end_date):
                url=os.path.join(k1m_url,obj,obj+"_"+d.strftime("%Y%m%d")+".pkl")
                k1ms=load(url)
                for i in k1ms:
                    if i["timekey"]<start_datetime:
                        continue
                    if i["timekey"]>end_datetime:
                        break
                    yield i
        else:
            url=os.path.join(k1m_url,obj)
            l=os.listdir(url)
            l.sort()
            isbreak=False
            for pkl in l:
                d=pkl.split(".")[0].split("_")[-1]
                if str2datetime(d)<start_date:
                    continue
                url0=os.path.join(url,pkl)
                k1ms = load(url0)
                n=0
                for i in k1ms:
                    if n>bars_len:
                        isbreak=True
                        break
                    if i["timekey"] < start_datetime:
                        continue
                    n=n+1
                    yield i
                if isbreak:
                    break
    else:
        end_datetime = str2datetime(end_datetime)
        if end_datetime.hour >= 18:
            end_date = tradecal.getnexttradeday(end_datetime)
        else:
            end_date = tradecal.gettradeday(end_datetime)
        url = os.path.join(k1m_url, obj)
        l = os.listdir(url)
        l.sort(reverse=True)
        isbreak = False
        for pkl in l:
            d = pkl.split(".")[0].split("_")[-1]
            if str2datetime(d) > end_date:
                continue
            url0 = os.path.join(url, pkl)
            k1ms = load(url0)
            n = 0
            for i in reversed(k1ms):
                if n > bars_len:
                    isbreak = True
                    break
                if i["timekey"] > end_datetime:
                    continue
                n = n + 1
                yield i
            if isbreak:
                break
def get_k1m_f_bypkl(obj,start_datetime=None,end_datetime=None,bars_len=30,k1m_url=r"D:\data\future_k1m_self"):
    if start_datetime:
        start_datetime=str2datetime(start_datetime)
        if start_datetime.hour>=18:
            start_date=tradecal.getnexttradeday(start_datetime)
        else:
            start_date = tradecal.gettradeday(start_datetime)
        if end_datetime:
            end_datetime=str2datetime(end_datetime)
            if end_datetime.hour >= 18:
                end_date = tradecal.getnexttradeday(end_datetime)
            else:
                end_date = tradecal.gettradeday(end_datetime)
            ticks=[]
            for d in get_calender(start_date,end_date):
                url=os.path.join(k1m_url,obj,obj+"_"+d.strftime("%Y%m%d")+".pkl")
                k1ms=load(url)
                for i in k1ms:
                    if i["timekey"]<start_datetime:
                        continue
                    if i["timekey"]>end_datetime:
                        break
                    ticks.append(i)
            return ticks
        else:
            url=os.path.join(k1m_url,obj)
            l=os.listdir(url)
            l.sort()
            isbreak=False

            ticks=[]
            for pkl in l:
                d=pkl.split(".")[0].split("_")[-1]
                if str2datetime(d)<start_date:
                    continue
                url0=os.path.join(url,pkl)
                k1ms = load(url0)
                n=1
                for i in k1ms:
                    if n>bars_len:
                        isbreak=True
                        break
                    if i["timekey"] < start_datetime:
                        continue
                    n=n+1
                    ticks.append(i)
                if isbreak:
                    break
            return ticks
    else:
        end_datetime = str2datetime(end_datetime)
        if end_datetime.hour >= 18:
            end_date = tradecal.getnexttradeday(end_datetime)
        else:
            end_date = tradecal.gettradeday(end_datetime)
        url = os.path.join(k1m_url, obj)
        l = os.listdir(url)
        l.sort(reverse=True)
        isbreak = False

        ticks = []
        for pkl in l:
            d = pkl.split(".")[0].split("_")[-1]
            if str2datetime(d) > end_date:
                continue
            url0 = os.path.join(url, pkl)
            k1ms = load(url0)
            n = 1
            for i in reversed(k1ms):
                if n > bars_len:
                    isbreak = True
                    break
                if i["timekey"] > end_datetime:
                    continue
                n = n + 1
                ticks.append(i)
            if isbreak:
                break
        return ticks
def gen_tick_f_bypkl(obj,start_datetime=None,end_datetime=None,ticks_len=30,k1m_url=r"D:\data\future"):
    if start_datetime:
        start_datetime=str2datetime(start_datetime)
        if start_datetime.hour>=18:
            start_date=tradecal.getnexttradeday(start_datetime)
        else:
            start_date = tradecal.gettradeday(start_datetime)
        if end_datetime:
            end_datetime=str2datetime(end_datetime)
            if end_datetime.hour >= 18:
                end_date = tradecal.getnexttradeday(end_datetime)
            else:
                end_date = tradecal.gettradeday(end_datetime)
            for d in get_calender(start_date,end_date):
                url=os.path.join(k1m_url,obj,obj+"_"+d.strftime("%Y%m%d")+".pkl")
                k1ms=load(url)
                for i in k1ms:
                    if i["timekey"]<start_datetime:
                        continue
                    if i["timekey"]>end_datetime:
                        break
                    yield i
        else:
            url=os.path.join(k1m_url,obj)
            l=os.listdir(url)
            l.sort()
            isbreak=False
            for pkl in l:
                d=pkl.split(".")[0].split("_")[-1]
                if str2datetime(d)<start_date:
                    continue
                url0=os.path.join(url,pkl)
                k1ms = load(url0)
                n=1
                for i in k1ms:
                    if n>ticks_len:
                        isbreak=True
                        break
                    if i["timekey"] < start_datetime:
                        continue
                    n=n+1
                    yield i
                if isbreak:
                    break
    else:
        end_datetime = str2datetime(end_datetime)
        if end_datetime.hour >= 18:
            end_date = tradecal.getnexttradeday(end_datetime)
        else:
            end_date = tradecal.gettradeday(end_datetime)
        url = os.path.join(k1m_url, obj)
        l = os.listdir(url)
        l.sort(reverse=True)
        isbreak = False
        for pkl in l:
            d = pkl.split(".")[0].split("_")[-1]
            if str2datetime(d) > end_date:
                continue
            url0 = os.path.join(url, pkl)
            k1ms = load(url0)
            n = 1
            for i in reversed(k1ms):
                if n > ticks_len:
                    isbreak = True
                    break
                if i["timekey"] > end_datetime:
                    continue
                n = n + 1
                yield i
            if isbreak:
                break
def get_tick_f_bypkl(obj,start_datetime=None,end_datetime=None,ticks_len=30,k1m_url=r"D:\data\future"):
    if start_datetime:
        start_datetime=str2datetime(start_datetime)
        if start_datetime.hour>=18:
            start_date=tradecal.getnexttradeday(start_datetime)
        else:
            start_date = tradecal.gettradeday(start_datetime)
        if end_datetime:
            end_datetime=str2datetime(end_datetime)
            if end_datetime.hour >= 18:
                end_date = tradecal.getnexttradeday(end_datetime)
            else:
                end_date = tradecal.gettradeday(end_datetime)
            ticks=[]
            for d in get_calender(start_date,end_date):
                url=os.path.join(k1m_url,obj,obj+"_"+d.strftime("%Y%m%d")+".pkl")
                k1ms=load(url)
                for i in k1ms:
                    if i["timekey"]<start_datetime:
                        continue
                    if i["timekey"]>end_datetime:
                        break
                    ticks.append(i)
            return ticks
        else:
            url=os.path.join(k1m_url,obj)
            l=os.listdir(url)
            l.sort()
            isbreak=False

            ticks=[]
            for pkl in l:
                d=pkl.split(".")[0].split("_")[-1]
                if str2datetime(d)<start_date:
                    continue
                url0=os.path.join(url,pkl)
                k1ms = load(url0)
                n=1
                for i in k1ms:
                    if n>ticks_len:
                        isbreak=True
                        break
                    if i["timekey"] < start_datetime:
                        continue
                    n=n+1
                    ticks.append(i)
                if isbreak:
                    break
            return ticks
    else:
        end_datetime = str2datetime(end_datetime)
        if end_datetime.hour >= 18:
            end_date = tradecal.getnexttradeday(end_datetime)
        else:
            end_date = tradecal.gettradeday(end_datetime)
        url = os.path.join(k1m_url, obj)
        l = os.listdir(url)
        l.sort(reverse=True)
        isbreak = False

        ticks = []
        for pkl in l:
            d = pkl.split(".")[0].split("_")[-1]
            if str2datetime(d) > end_date:
                continue
            url0 = os.path.join(url, pkl)
            k1ms = load(url0)
            n = 1
            for i in reversed(k1ms):
                if n > ticks_len:
                    isbreak = True
                    break
                if i["timekey"] > end_datetime:
                    continue
                n = n + 1
                ticks.append(i)
            if isbreak:
                break
        return ticks
def get_settle_price(obj,timekey):
    if timekey.hour>=18:
        d=datetime.datetime(timekey.year,timekey.month,timekey.day)
    else:
        d=tradecal.getpretradeday(timekey)
    db=getdb_client()
    i=db["future_k1d"].find_one({"obj":obj,"timekey":d})
    db.client.close()
    return i["settle"]
def get_prek1d(obj,timekey):
    if timekey.hour>=18:
        d=datetime.datetime(timekey.year,timekey.month,timekey.day)
    else:
        d=tradecal.getpretradeday(timekey)
    db=getdb_client()
    i=db["future_k1d"].find_one({"obj":obj,"timekey":d})
    db.client.close()
    return i
def get_k1d(obj,timekey):
    if timekey.hour>=18:
        d=tradecal.getnexttradeday(timekey)
    else:
        d=datetime.datetime(timekey.year,timekey.month,timekey.day)
    db=getdb_client()
    i=db["future_k1d"].find_one({"obj":obj,"timekey":d})
    db.client.close()
    return i["settle"]
def getk1m_f_bymongo(obj,start_datetime,end_datetime=None,bars_len=None):
    pass
if __name__ == '__main__':
    # t0 = get_k1m_f_bypkl(obj="TA101", start_datetime="20200831 22:00", end_datetime="20200901 10:00", bars_len=20)
    # t1 = get_k1m_f_bypkl(obj="TA101", start_datetime="20200831 22:00", end_datetime=None,bars_len=20)
    # t2 = get_k1m_f_bypkl(obj="TA101", start_datetime=None, end_datetime="20200831 22:00", bars_len=20)
    # t00=[]
    # for i in gen_k1m_f_bypkl(obj="TA101", start_datetime="20200831 22:00", end_datetime="20200901 10:00", bars_len=20):
    #     t00.append(i)
    # t10 = []
    # for i in get_k1m_f_bypkl(obj="TA101", start_datetime="20200831 22:00", end_datetime=None,bars_len=20):
    #     t10.append(i)
    # t20 = []
    # for i in get_k1m_f_bypkl(obj="TA101", start_datetime=None, end_datetime="20200831 22:00", bars_len=20):
    #     t20.append(i)

    # t0 = get_tick_f_bypkl(obj="TA101", start_datetime="20200831 22:00", end_datetime="20200901 10:00", ticks_len=20)
    # t1 = get_tick_f_bypkl(obj="TA101", start_datetime="20200831 22:00", end_datetime=None,ticks_len=20)
    # t2 = get_tick_f_bypkl(obj="TA101", start_datetime=None, end_datetime="20200831 22:00", ticks_len=20)
    # t00=[]
    # for i in gen_tick_f_bypkl(obj="TA101", start_datetime="20200831 22:00", end_datetime="20200901 10:00", ticks_len=20):
    #     t00.append(i)
    # t10 = []
    # for i in gen_tick_f_bypkl(obj="TA101", start_datetime="20200831 22:00", end_datetime=None,ticks_len=20):
    #     t10.append(i)
    # t20 = []
    # for i in gen_tick_f_bypkl(obj="TA101", start_datetime=None, end_datetime="20200831 22:00", ticks_len=20):
    #     t20.append(i)

    print(get_settle_price("TA",datetime.datetime(2023,1,30,9)))
    print(get_settle_price("TA", datetime.datetime(2023, 1, 30, 21)))
    print("end")